package com.erpanderp.wam.usm.view.leave;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.erpanderp.wam.adm.model.entity.Role;
import com.erpanderp.wam.adm.model.service.RoleDAO;
import com.erpanderp.wam.tm.model.service.RRFDAO;
import com.erpanderp.wam.usm.model.entity.leave.EmployeeLeave;
import com.erpanderp.wam.usm.model.entity.leave.LeaveType;
import com.erpanderp.wam.usm.model.entity.user.Employee;
import com.erpanderp.wam.usm.model.entity.user.WAMUser;
import com.erpanderp.wam.usm.model.service.leave.EmployeeLeaveDAO;
import com.erpanderp.wam.usm.model.service.leave.LeaveTypeDAO;
import com.erpanderp.wam.util.CommonLookup;
import com.erpanderp.wam.util.EmailUtil;
import com.erpanderp.wam.util.ValidationUtil;
import com.erpanderp.wam.util.WAMHostManager;
import com.erpanderp.wam.util.model.entity.WAMEmail;
@ManagedBean
@ViewScoped
public class ApplyLeaveBean implements Serializable {

ServletContext context = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
	
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
private WAMUser wamUser = new WAMUser();
private RRFDAO rrfDAO = new RRFDAO();
private static final long serialVersionUID = 1L;
private Map<String, Long> leaveTypesMap = new HashMap<String, Long>();
private String empName;
private Employee reportingManager;
private String reportingManagerName;
private Long noOfDays;
private String contactNumber;
LeaveTypeDAO leaveTypeDAO = new LeaveTypeDAO();
private String availableAddress;
private String reasonForLeave;
private Date leaveFrom;
private Date leaveTo;
private List<LeaveType> leaveTypes = new ArrayList<LeaveType>();
private Long selectedLeaveTypeId;
private LeaveType leaveType = new LeaveType();
private EmployeeLeave employeeLeave = new EmployeeLeave();
private EmployeeLeaveDAO employeeLeaveDAO = new EmployeeLeaveDAO();
private boolean detailsForConfirmLeave;
private boolean FORM_VALID;
private WAMEmail wamEmail = new WAMEmail();
private String messageText;
private String leaveCODE;
private EmailUtil emailUtil;

public ApplyLeaveBean() {
	
	
	System.out.println("GENERATED LEAVE CODE :"+leaveCODE);
	wamUser = (WAMUser) session.getAttribute(CommonLookup.SESSION_ATTRIBUTE_WAMUSER);
	if(wamUser != null){
	empName = wamUser.getEmployee().getFirstName();
	reportingManager = rrfDAO.getReportingManager(wamUser.getEmployee().getEmployeeId());
	reportingManagerName = reportingManager.getFirstName();
	setDetailsForConfirmLeave(false);
	leaveTypes = leaveTypeDAO.getLeaveTypes();
	for (LeaveType leaveType : leaveTypes) {
		leaveTypesMap.put(leaveType.getLeaveType(), leaveType.getLeaveTypeid());
	}
	}else{
		ValidationUtil.gotoLoginPage();
	}
}

public void applyLeaveAction(ActionEvent e){
	SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
	//String fromDate = formatter.format(employeeLeave.getPeriodFrom());
	//String toDate = formatter.format(employeeLeave.getPeriodTo());
	System.out.println("IN APPLY LEAVE ACTION");
	validate();
	if(FORM_VALID){
		emailUtil = new EmailUtil();
		System.out.println("SELECTED LEAVE TYPE ID ="+selectedLeaveTypeId);
		leaveType = leaveTypeDAO.getLeaveTypeById(selectedLeaveTypeId);
		//employeeLeave.setAppliedOn(appliedOn);
		boolean emailSent = false;
		employeeLeave.setLeaveType(leaveType);
		leaveCODE = CommonLookup.getAutoGeneratedLeaveCODE(leaveType,wamUser.getEmployeeCode());
		System.out.println("LEAVE CODE IS ="+leaveCODE);
		employeeLeave.setLeaveCode(leaveCODE);
		employeeLeave.setCreateDate(new Date());
		employeeLeave.setApprovalStatus(CommonLookup.LEAVE_INPROCESS_STATUS);
		employeeLeave.setStatus("ACTIVE");
		employeeLeave.setCreatedBy(wamUser.getEmployee().getFirstName());
		
		employeeLeave.setEmployee(wamUser.getEmployee());
		employeeLeaveDAO.employeeLeaveApply(employeeLeave);
		//FacesMessage msg = new FacesMessage("Leave apllied successfully from",null,null);
      //  FacesContext.getCurrentInstance().addMessage(null, msg); "+fromDate+" to "+toDate
       
      
		//  String[] to = {reportingManager.getEmail(),"dayasankar.s@erpanderp.com"};
        emailUtil = new EmailUtil();
		Map<String, String> hostsMap = WAMHostManager.getWAMHosts(context);

		if(hostsMap.get(CommonLookup.DEV_EMAIL) == null){

		String[] to = {reportingManager.getEmail()};
		emailUtil.setRecieverAddresses(to);
	}else{
		String[] to = {hostsMap.get(CommonLookup.DEV_EMAIL)};
		emailUtil.setRecieverAddresses(to);
	}
        
		
		
        String activationLink = "http://";
        String serverName = request.getServerName();
        String port = String.valueOf(request.getServerPort());
        String requestURL = "wam/login.xhtml";
        if(port != null && port.equals("80")){
        	activationLink += (serverName+requestURL+"?leaveCODE="+leaveCODE+"&EMPID"+wamUser.getEmployeeCode());
        }else{
        	activationLink += (serverName+":"+port+requestURL+"?leaveCODE="+leaveCODE+"&EMPID"+wamUser.getEmployeeCode());
        }
        String messageString = "Dear " + reportingManager.getFirstName() + " " + reportingManager.getLastName() + ",<br /><br />" + 
				
								"Thank you for registering with podquick.com<br /> <br />"+
						         
						         "<b><u>Your Login Details :</u></b><br />"+
						         
						         "<table border='0'>"+
						         "<tr> <td>Employee id </td><td> : </td><td>"+wamUser.getEmployee().getEmployeeCode()+" </td></tr>"+
						         "<tr> <td>Employee name</td><td> : </td> <td>"+wamUser.getEmployee().getFirstName()+"</td></tr>"+
						         "<tr> <td>Employee available contact number</td><td> : </td> <td>"+employeeLeave.getEmployee().getTelephone()+"</td></tr>"+
						         "<tr> <td>Available address</td><td> : </td> <td>"+employeeLeave.getAvailableAddress()+"</td></tr>"+
						         "<tr> <td>Reason for leave</td><td> : </td> <td>"+employeeLeave.getReason()+"</td></tr>"+
						         "</table><br/>"+								
						         "<a style='color:#FF9933;font-weight: bold;' href=\""+
								 activationLink + "\">" + "Please click here to approve/reject leave request" + "</a /><br /><br />"+
								 "(Employees who are in Hyderabad office)"+
								 
								"Thanks & Regards, <br />WAM - Dev TEAM";
        //emailUtil.setRecieverAddresses();
       
       // emailUtil.setRecieverAddresses(to);
        emailUtil.setSenderEmail("podquick@erpanderp.com", "WAM - Dev Team");
        emailUtil.setSubject("WAM - Leave Request");
        String WAMEmailStatus = emailUtil.processAndSendEmail();
        if(WAMEmailStatus.equals(CommonLookup.EMAIL_SENT_AND_RECORDED)){
        	
        }else if(WAMEmailStatus.equals(CommonLookup.EMAIL_SENT_AND_NOT_RECORDED)){
        	
        }else if(WAMEmailStatus.equals(CommonLookup.EMAIL_FAILED_AND_RECORDED)){
        	
        }else{
        	
        }
        employeeLeave = new EmployeeLeave();
	}
	
} 

public void confirmLeaveBeforeApply(){
	System.out.println("IN CONFIEM LEAVE ACTION");
	noOfDays = daysBetween(employeeLeave.getPeriodTo(),employeeLeave.getPeriodFrom());
	
}

public long daysBetween(Date max, Date min)
{
 System.out.println("IN DAYSBETWEEN METHOD");
 System.out.println("MAX DATE :"+max);
 System.out.println("MIN DATE :"+min);
 return (max.getTime() - min.getTime())/86400000;
}


public boolean validate(){
	System.out.println("IN VALIDATE METHOD");
	FORM_VALID = true;
	if(ValidationUtil.isEmpty(new Long(selectedLeaveTypeId).toString(), "Leave Type", null, FacesContext.getCurrentInstance()) != null){
		System.out.println("LEAVE TYPE IS EMPTY");
		
		FORM_VALID = false;
		
	}
	
	if(ValidationUtil.isEmpty((employeeLeave.getPeriodFrom() != null) ? employeeLeave.getPeriodFrom().toString() : null, "Leave From", null, FacesContext.getCurrentInstance()) != null){
		FORM_VALID = false;
		System.out.println("LEAVE FORM IS EMPTY");
	}
	if(ValidationUtil.isEmpty((employeeLeave.getPeriodTo() != null) ? employeeLeave.getPeriodTo().toString() : null, "Leave To", null, FacesContext.getCurrentInstance()) != null){
		FORM_VALID = false;
		System.out.println("LEAVE TO IS EMPTY");
	}
	if(ValidationUtil.isEmpty(employeeLeave.getAvailableAddress(), "Available Address", null, FacesContext.getCurrentInstance()) != null){
		FORM_VALID = false;
		System.out.println("AVAILABLE ADDRESS IS EMPTY");
	}
	if(ValidationUtil.isEmpty(employeeLeave.getReason(), "Reason For Leave", null, FacesContext.getCurrentInstance()) != null){
		FORM_VALID = false;
		System.out.println("REASON FOR LEAVE IS EMPTY");
	}
	return FORM_VALID;
}

//GETTERS AND SETTERS

public LeaveTypeDAO getLeaveTypeDAO() {
	return leaveTypeDAO;
}

public void setLeaveTypeDAO(LeaveTypeDAO leaveTypeDAO) {
	this.leaveTypeDAO = leaveTypeDAO;
}

public boolean isDetailsForConfirmLeave() {
	return detailsForConfirmLeave;
}

public void setDetailsForConfirmLeave(boolean detailsForConfirmLeave) {
	this.detailsForConfirmLeave = detailsForConfirmLeave;
}
public List<LeaveType> getLeaveTypes() {
	return leaveTypes;
}

public void setLeaveTypes(List<LeaveType> leaveTypes) {
	this.leaveTypes = leaveTypes;
}

public Map<String, Long> getLeaveTypesMap() {
	return leaveTypesMap;
}

public void setLeaveTypesMap(Map<String, Long> leaveTypesMap) {
	this.leaveTypesMap = leaveTypesMap;
}

public Long getSelectedLeaveTypeId() {
	return selectedLeaveTypeId;
}

public void setSelectedLeaveTypeId(Long selectedLeaveTypeId) {
	this.selectedLeaveTypeId = selectedLeaveTypeId;
}


public WAMUser getWamUser() {
	return wamUser;
}

public void setWamUser(WAMUser wamUser) {
	this.wamUser = wamUser;
}

public String getEmpName() {
	return empName;
}

public void setEmpName(String empName) {
	this.empName = empName;
}

public Employee getReportingManager() {
	return reportingManager;
}


public void setReportingManager(Employee reportingManager) {
	this.reportingManager = reportingManager;
}

public RRFDAO getRrfDAO() {
	return rrfDAO;
}

public void setRrfDAO(RRFDAO rrfDAO) {
	this.rrfDAO = rrfDAO;
}




public String getReportingManagerName() {
	return reportingManagerName;
}




public void setReportingManagerName(String reportingManagerName) {
	this.reportingManagerName = reportingManagerName;
}


public Long getNoOfDays() {
	return noOfDays;
}


public void setNoOfDays(Long noOfDays) {
	this.noOfDays = noOfDays;
}




public String getContactNumber() {
	return contactNumber;
}




public void setContactNumber(String contactNumber) {
	this.contactNumber = contactNumber;
}

public boolean isFORM_VALID() {
	return FORM_VALID;
}

public void setFORM_VALID(boolean fORM_VALID) {
	FORM_VALID = fORM_VALID;
}

public String getAvailableAddress() {
	return availableAddress;
}

public void setAvailableAddress(String availableAddress) {
	this.availableAddress = availableAddress;
}

public String getReasonForLeave() {
	return reasonForLeave;
}

public void setReasonForLeave(String reasonForLeave) {
	this.reasonForLeave = reasonForLeave;
}

public Date getLeaveFrom() {
	return leaveFrom;
}

public void setLeaveFrom(Date leaveFrom) {
	this.leaveFrom = leaveFrom;
}

public Date getLeaveTo() {
	return leaveTo;
}

public void setLeaveTo(Date leaveTo) {
	this.leaveTo = leaveTo;
}

public EmployeeLeave getEmployeeLeave() {
	return employeeLeave;
}

public void setEmployeeLeave(EmployeeLeave employeeLeave) {
	this.employeeLeave = employeeLeave;
}

public LeaveType getLeaveType() {
	return leaveType;
}

public void setLeaveType(LeaveType leaveType) {
	this.leaveType = leaveType;
}

public EmployeeLeaveDAO getEmployeeLeaveDAO() {
	return employeeLeaveDAO;
}

public void setEmployeeLeaveDAO(EmployeeLeaveDAO employeeLeaveDAO) {
	this.employeeLeaveDAO = employeeLeaveDAO;
}

public WAMEmail getWamEmail() {
	return wamEmail;
}

public void setWamEmail(WAMEmail wamEmail) {
	this.wamEmail = wamEmail;
}

public String getMessageText() {
	return messageText;
}

public void setMessageText(String messageText) {
	this.messageText = messageText;
}

public String getLeaveCODE() {
	return leaveCODE;
}

public void setLeaveCODE(String leaveCODE) {
	this.leaveCODE = leaveCODE;
}

public EmailUtil getEmailUtil() {
	return emailUtil;
}

public void setEmailUtil(EmailUtil emailUtil) {
	this.emailUtil = emailUtil;
}


}
